<template>
  <el-dialog
    v-model="formVisible"
    :title="title"
    :append-to-body="true"
    @close="closeDialog"
    destroy-on-close
    width="500px"
  >
    <el-form
      :model="dictForm"
      :rules="dictFormrules"
      ref="dictFormRef"
      label-width="80"
      label-position="right"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="dictForm.name"></el-input>
      </el-form-item>
      <el-form-item label="描述名称" prop="description">
        <el-input
          v-model="dictForm.description"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="modal-footer">
      <el-button @click="saveDic" :icon="Plus" type="primary">保存</el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";
import { getdictionaryinfo, editdictionaryinfo, adddictionary } from "@/api/dict/index";
const props = defineProps({
  dictId: { type: String, default: null },
});
const isEdit = ref<boolean>(false);
const title = ref<string>("添加字典");
const formVisible = ref<boolean>(true);
const emit = defineEmits(["closedialogevent", "refresh"]);
const dictFormRef = ref<FormInstance>();
const dictFormrules = ref({
  name: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
});
const dictForm = ref<any>({
  name: "",
  description: "",
});
const saveDic = () => {
  let param = { ...dictForm.value };
  dictFormRef.value?.validate((valid: boolean) => {
    if (valid) {

      if (isEdit.value) {
        editdictionaryinfo(props.dictId, param).then((res) => {
          ElNotification({
            title: "提示",
            message: "修改成功",
            type: "success",
            duration: 2000,
          });
          closeDialog();
          emit("refresh");
        });
      } else {
        adddictionary(param).then((res) => {
          ElNotification({
            title: "提示",
            message: "添加成功",
            type: "success",
            duration: 2000,
          });
          closeDialog();
          emit("refresh");
        });
      }
    }
  });
  //console.log(param);
};
const closeDialog = () => {
  formVisible.value = false;
  emit("closedialogevent", formVisible.value);
};

const edit_init = () => {
  let dicId = props.dictId;
  getdictionaryinfo(dicId).then((res) => {
    dictForm.value = res;
  });
};
onMounted(() => {
  if (props.dictId == null) {
    isEdit.value = false;
    title.value = "添加字典";
  } else {
    isEdit.value = true;
    title.value = "编辑字典";
    edit_init();
  }
});
</script>
